﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace oop_5_server
{
    struct sPost
    {
        public Post post;
        public ArrayList awaitingUsers;
    }

    /// <summary>
    /// PostManager - менеджер сообщений.
    /// </summary>
    /// <li>
    /// <lu>Реализует паттерн Медиатор, забирая на себя практически полностью организацию обмена сообщениями между клиентами.</lu>
    /// <lu></lu>
    /// </li>

    class PostManager
    {
        protected ArrayList Posts;
        protected UserManager Users;
        protected CSDB DBConnection;

        public PostManager(ref UserManager users, ref CSDB connection)
        {
            Posts = new ArrayList();
            Users = users;
            DBConnection = connection;
        }

        protected bool SavePost(Post ps)
        {
            int max_id = 1;
            try
            {
                max_id = DBConnection.Posts.Max(p => p.id);
                max_id++;
            }
            catch
            {
                max_id = 1;
            }

            ps.id = max_id;

            DBConnection.Posts.InsertOnSubmit(ps);

            try
            {
                DBConnection.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return false;
            }
            finally
            {
                sPost sps = new sPost { post = ps };
                sps.awaitingUsers = (ArrayList)Users.List.Clone();
                if (ps.@private != null)
                {
                    sps.awaitingUsers.Clear();
                    foreach (sUser user in Users.List)
                    {
                        if (user.userkey == ps.@private || user.userkey == ps.userkey )
                        {
                            sps.awaitingUsers.Add(user);
                        }
                    }
                }
                Posts.Add(sps);
            }

            return true;
        }

        protected void BroadcastMessage()
        {

        }

        public bool Post(Post post)
        {
            bool saved = this.SavePost(post);
            this.BroadcastMessage();
            return saved;
        }

        public Packet GetPostsForUser(string userkey)
        {
            ArrayList checkedPost = new ArrayList();

            Packet postsResp = new Packet();
            int postRespK = 1;
            foreach (sPost post in Posts)
            {
                bool gotPost = false;
                sUser ruser = new sUser();
                foreach (sUser user in post.awaitingUsers)
                {
                    if (user.userkey == userkey)
                    {
                        ruser = user;
                        gotPost = true;
                        break;
                    }
                }
                if (gotPost)
                {
                    checkedPost.Add(post);

                    post.awaitingUsers.Remove(ruser);

                    Packet postResp = new Packet();

                    int unixTime = (int)(post.post.time - new DateTime(1970, 1, 1)).TotalSeconds;
                    postResp.Add("username", Users.GetUsernameByKey(post.post.userkey));
                    postResp.Add("userkey", post.post.userkey);
                    postResp.Add("text", post.post.text);
                    postResp.Add("time", unixTime.ToString());

                    if (post.post.@private == null)
                    {
                        postResp.Add("private", "false");
                    }
                    else
                    {
                        postResp.Add("private", post.post.@private);
                        postResp.Add("privatename", Users.GetUsernameByKey(post.post.@private));
                    }
                    postsResp.Add((postRespK++).ToString(), postResp);
                }
            }

            foreach (sPost post in checkedPost)
            {
                if (post.awaitingUsers != null && post.awaitingUsers.Count == 0)
                {
                    Posts.Remove(post);
                }
            }

            return postsResp;
        }


    }
}
